import 'package:flutter/material.dart';
import '../constants/app_theme.dart';
import '../constants/app_constants.dart';

/// 标签输入组件
/// 用于添加和管理标签
class TagInput extends StatefulWidget {
  /// 当前标签列表
  final List<String> tags;
  
  /// 标签变化回调
  final Function(List<String>) onTagsChanged;
  
  /// 主题颜色
  final Color? color;
  
  /// 最大标签数量
  final int maxTags;
  
  /// 是否只读
  final bool readOnly;
  
  /// 建议标签列表
  final List<String>? suggestedTags;

  const TagInput({
    super.key,
    required this.tags,
    required this.onTagsChanged,
    this.color,
    this.maxTags = AppConstants.maxTagsPerRecord,
    this.readOnly = false,
    this.suggestedTags,
  });

  @override
  State<TagInput> createState() => _TagInputState();
}

class _TagInputState extends State<TagInput> {
  final TextEditingController _controller = TextEditingController();
  final FocusNode _focusNode = FocusNode();
  List<String> _currentTags = [];
  bool _showSuggestions = false;
  List<String> _filteredSuggestions = [];

  @override
  void initState() {
    super.initState();
    _currentTags = List.from(widget.tags);
    _setupSuggestions();
    _controller.addListener(_onTextChanged);
    _focusNode.addListener(_onFocusChanged);
  }

  @override
  void dispose() {
    _controller.dispose();
    _focusNode.dispose();
    super.dispose();
  }

  @override
  void didUpdateWidget(TagInput oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.tags != widget.tags) {
      _currentTags = List.from(widget.tags);
    }
    if (oldWidget.suggestedTags != widget.suggestedTags) {
      _setupSuggestions();
    }
  }

  /// 设置建议标签
  void _setupSuggestions() {
    if (widget.suggestedTags != null) {
      _filteredSuggestions = widget.suggestedTags!
          .where((tag) => !_currentTags.contains(tag))
          .toList();
    } else {
      _filteredSuggestions = AppConstants.defaultTags
          .where((tag) => !_currentTags.contains(tag))
          .toList();
    }
  }

  /// 文本变化处理
  void _onTextChanged() {
    final text = _controller.text.toLowerCase();
    if (text.isEmpty) {
      setState(() {
        _filteredSuggestions = (widget.suggestedTags ?? AppConstants.defaultTags)
            .where((tag) => !_currentTags.contains(tag))
            .toList();
      });
    } else {
      setState(() {
        _filteredSuggestions = (widget.suggestedTags ?? AppConstants.defaultTags)
            .where((tag) => 
                !_currentTags.contains(tag) && 
                tag.toLowerCase().contains(text))
            .toList();
      });
    }
  }

  /// 焦点变化处理
  void _onFocusChanged() {
    setState(() {
      _showSuggestions = _focusNode.hasFocus && !widget.readOnly;
    });
  }

  /// 添加标签
  void _addTag(String tag) {
    final trimmedTag = tag.trim();
    
    if (trimmedTag.isEmpty) return;
    if (_currentTags.contains(trimmedTag)) return;
    if (_currentTags.length >= widget.maxTags) {
      _showMaxTagsMessage();
      return;
    }
    if (!AppConstants.isValidTag(trimmedTag)) {
      _showInvalidTagMessage();
      return;
    }

    setState(() {
      _currentTags.add(trimmedTag);
      _controller.clear();
      _setupSuggestions();
    });
    
    widget.onTagsChanged(_currentTags);
  }

  /// 删除标签
  void _removeTag(String tag) {
    setState(() {
      _currentTags.remove(tag);
      _setupSuggestions();
    });
    
    widget.onTagsChanged(_currentTags);
  }

  /// 显示最大标签数量提示
  void _showMaxTagsMessage() {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text('最多只能添加 ${widget.maxTags} 个标签'),
        backgroundColor: AppTheme.warningColor,
        behavior: SnackBarBehavior.floating,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(8),
        ),
      ),
    );
  }

  /// 显示无效标签提示
  void _showInvalidTagMessage() {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: const Text('标签格式不正确，请使用中文、英文或数字'),
        backgroundColor: AppTheme.errorColor,
        behavior: SnackBarBehavior.floating,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(8),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final themeColor = widget.color ?? AppTheme.primaryColor;
    
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 标签显示区域
        if (_currentTags.isNotEmpty)
          _buildTagsDisplay(themeColor),
        
        if (_currentTags.isNotEmpty && !widget.readOnly)
          const SizedBox(height: 12),
        
        // 输入区域
        if (!widget.readOnly)
          _buildInputField(themeColor),
        
        // 建议标签
        if (_showSuggestions && _filteredSuggestions.isNotEmpty)
          _buildSuggestions(themeColor),
      ],
    );
  }

  /// 构建标签显示区域
  Widget _buildTagsDisplay(Color themeColor) {
    return Wrap(
      spacing: 8,
      runSpacing: 8,
      children: _currentTags.map((tag) {
        return _buildTagChip(tag, themeColor);
      }).toList(),
    );
  }

  /// 构建标签芯片
  Widget _buildTagChip(String tag, Color themeColor) {
    return Container(
      padding: const EdgeInsets.symmetric(
        horizontal: 12,
        vertical: 6,
      ),
      decoration: BoxDecoration(
        color: themeColor.withValues(alpha: 0.1),
        borderRadius: BorderRadius.circular(16),
        border: Border.all(
          color: themeColor.withValues(alpha: 0.3),
        ),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            tag,
            style: TextStyle(
              color: themeColor,
              fontSize: 14,
              fontWeight: FontWeight.w500,
            ),
          ),
          if (!widget.readOnly) ...{
            const SizedBox(width: 4),
            GestureDetector(
              onTap: () => _removeTag(tag),
              child: Icon(
                Icons.close,
                size: 16,
                color: themeColor,
              ),
            ),
          },
        ],
      ),
    );
  }

  /// 构建输入框
  Widget _buildInputField(Color themeColor) {
    return TextField(
      controller: _controller,
      focusNode: _focusNode,
      decoration: InputDecoration(
        hintText: _currentTags.length >= widget.maxTags
            ? '已达到最大标签数量'
            : '添加标签（按回车确认）',
        hintStyle: TextStyle(
          color: AppTheme.textSecondaryColor,
        ),
        prefixIcon: Icon(
          Icons.local_offer_outlined,
          color: AppTheme.textSecondaryColor,
        ),
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: BorderSide(
            color: AppTheme.dividerColor,
          ),
        ),
        focusedBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: BorderSide(
            color: themeColor,
            width: 2,
          ),
        ),
        filled: true,
        fillColor: AppTheme.surfaceColor,
        enabled: _currentTags.length < widget.maxTags,
      ),
      style: TextStyle(
        color: AppTheme.textPrimaryColor,
      ),
      textInputAction: TextInputAction.done,
      onSubmitted: _addTag,
      maxLength: AppConstants.maxTagLength,
      buildCounter: (context, {required currentLength, required isFocused, maxLength}) {
        if (!isFocused || maxLength == null) return null;
        return Text(
          '$currentLength/$maxLength',
          style: TextStyle(
            color: AppTheme.textSecondaryColor,
            fontSize: 12,
          ),
        );
      },
    );
  }

  /// 构建建议标签
  Widget _buildSuggestions(Color themeColor) {
    return Container(
      margin: const EdgeInsets.only(top: 8),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: AppTheme.surfaceColor,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(
          color: AppTheme.dividerColor,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '建议标签',
            style: TextStyle(
              color: AppTheme.textSecondaryColor,
              fontSize: 12,
              fontWeight: FontWeight.w500,
            ),
          ),
          const SizedBox(height: 8),
          Wrap(
            spacing: 6,
            runSpacing: 6,
            children: _filteredSuggestions.take(10).map((tag) {
              return GestureDetector(
                onTap: () => _addTag(tag),
                child: Container(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 8,
                    vertical: 4,
                  ),
                  decoration: BoxDecoration(
                    color: themeColor.withValues(alpha: 0.05),
                    borderRadius: BorderRadius.circular(12),
                    border: Border.all(
                      color: themeColor.withValues(alpha: 0.2),
                    ),
                  ),
                  child: Text(
                    tag,
                    style: TextStyle(
                      color: themeColor,
                      fontSize: 12,
                    ),
                  ),
                ),
              );
            }).toList(),
          ),
        ],
      ),
    );
  }
}

/// 简单标签显示组件
/// 用于只读显示标签列表
class TagDisplay extends StatelessWidget {
  /// 标签列表
  final List<String> tags;
  
  /// 主题颜色
  final Color? color;
  
  /// 最大显示数量
  final int? maxCount;
  
  /// 标签大小
  final double fontSize;
  
  /// 是否紧凑模式
  final bool compact;

  const TagDisplay({
    super.key,
    required this.tags,
    this.color,
    this.maxCount,
    this.fontSize = 12,
    this.compact = false,
  });

  @override
  Widget build(BuildContext context) {
    if (tags.isEmpty) {
      return const SizedBox.shrink();
    }

    final themeColor = color ?? AppTheme.primaryColor;
    final displayTags = maxCount != null
        ? tags.take(maxCount!).toList()
        : tags;
    final hasMore = maxCount != null && tags.length > maxCount!;

    return Wrap(
      spacing: compact ? 4 : 6,
      runSpacing: compact ? 4 : 6,
      children: [
        ...displayTags.map((tag) {
          return Container(
            padding: EdgeInsets.symmetric(
              horizontal: compact ? 6 : 8,
              vertical: compact ? 2 : 4,
            ),
            decoration: BoxDecoration(
              color: themeColor.withValues(alpha: 0.1),
              borderRadius: BorderRadius.circular(compact ? 8 : 12),
              border: Border.all(
                color: themeColor.withValues(alpha: 0.3),
                width: 0.5,
              ),
            ),
            child: Text(
              tag,
              style: TextStyle(
                color: themeColor,
                fontSize: fontSize,
                fontWeight: FontWeight.w500,
              ),
            ),
          );
        }),
        
        if (hasMore)
          Container(
            padding: EdgeInsets.symmetric(
              horizontal: compact ? 6 : 8,
              vertical: compact ? 2 : 4,
            ),
            decoration: BoxDecoration(
              color: AppTheme.textSecondaryColor.withValues(alpha: 0.1),
              borderRadius: BorderRadius.circular(compact ? 8 : 12),
              border: Border.all(
                color: AppTheme.textSecondaryColor.withValues(alpha: 0.3),
                width: 0.5,
              ),
            ),
            child: Text(
              '+${tags.length - maxCount!}',
              style: TextStyle(
                color: AppTheme.textSecondaryColor,
                fontSize: fontSize,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
      ],
    );
  }
}